import 'dart:async';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:fate_blind_box/chat_view/chat_net_image.dart';
import 'package:fate_blind_box/im/person_info.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/widget/common_empty_view.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../im/addindex.dart';
import '../../utils/loading.dart';
import '../../utils/map/map_common_config.dart';
import 'contact_main_controller.dart';
import 'model/shop_matchmaker_list_model.dart';

//通讯录首页
class ContactUi extends StatefulWidget {
  const ContactUi({Key? key}) : super(key: key);

  @override
  State<ContactUi> createState() => _ContactUiState();
}

class _ContactUiState extends State<ContactUi>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  final List _tabs = [
    '好友',
    '粉丝',
    '群聊',
    // '商家',
  ];
  List addmessage = [];

  // 创建Controller
  late TabController _tabController;
  final ScrollController _scrollController = ScrollController(); //listview的控制器
  final int _page = 1; //加载的页数
  bool isLoading = false; //是否正在加载数据
  int _index = 0;
  List<String> lists = [];

  final List _listData = [];

  late double _screenWidth;

  ContactMainController contactMainController =
      Get.put(ContactMainController());

  late StreamSubscription<Map<String, Object>> _locationListener;

  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  _onTabChanged() {
    if (_tabController.index.toDouble() == _tabController.animation?.value) {
      //赋值 并更新数据
      _index = _tabController.index;
      // if (_index == _tabs.length - 1) {
      //   // if(CommonConfig.isHuaWeiPermission){
      //   //   isOpenLocationPermission().then((value) {
      //   //     contactMainController.isShowPermission = value;
      //   //     contactMainController.update([contactMainController.showPermissionViewId]);
      //   //   });
      //   // }
      //   if (Platform.isAndroid) {
      //     isOpenLocationPermission().then((value) {
      //       contactMainController.isShowPermission = value;
      //       contactMainController
      //           .update([contactMainController.showPermissionViewId]);
      //     });
      //   }
      //   getCurrentLocation();
      // }
      gettype(_index);
      _listData == [];
      _listData.clear();
      _getListData(_page, _index);
      setState(() {});
    }
  }

  Future<bool> isOpenLocationPermission() async {
    var status = await Permission.location.status;
    if (status.isGranted) {
      return false;
    }
    return true;
  }

  /// 上拉加载更多
  Future _getMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      await Future.delayed(const Duration(seconds: 1), () {});
    }
  }

  @override
  void initState() {
    super.initState();
    initdata();
    _getListData(_page, 0);
    _tabController =
        TabController(initialIndex: _index, length: _tabs.length, vsync: this);
    _tabController.addListener(() => _onTabChanged());
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });

    setState(() {});
  }

  void initdata() async {
    lists =
        await EMClient.getInstance.contactManager.getAllContactsFromServer();
    if (lists.isNotEmpty) {
      print('---------------mmmm' + lists.toString());

      //保存好友信息
      setMessagelist(lists, '2');
    }
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  //监听程序进入前后台的状态改变的方法
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      ///进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        debugPrint("应用进入前台======");
        break;

      ///应用状态处于闲置状态，并且没有用户的输入事件，
      // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        debugPrint("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
      //当前页面即将退出
      case AppLifecycleState.detached:
        debugPrint("当前页面即将退出======");
        break;
      // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        debugPrint("应用处于不可见状态 后台======");
        break;
      case AppLifecycleState.hidden:
        debugPrint("页面隐藏======");
        break;
    }
  }

  /// 下拉刷新方法,为list重新赋值
  Future<void> _onRefresh() async {
    await Future.delayed(const Duration(seconds: 3), () {});
  }

  /// 加载更多时显示的组件,给用户提示
  Widget _getMoreWidget() {
    return Center(
      child: Offstage(
        offstage: !isLoading,
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }

  Widget gettype(int index) {
    print('----------------' + index.toString());
    if (index == 0) {
      return SizedBox(
        height: 500,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Center(
              child: Image.asset(
                'images/no_data.png',
                width: 175,
                height: 122,
              ),
            ),
          ],
        ),
      );
    } else if (index == 1) {
      return SizedBox(
        height: 500,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Center(
              child: Image.asset(
                'images/no_data.png',
                width: 175,
                height: 122,
              ),
            ),
          ],
        ),
      );
    } else if (index == 2) {
      return SizedBox(
        height: 500,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Center(
              child: Image.asset(
                'images/no_data.png',
                width: 175,
                height: 122,
              ),
            ),
          ],
        ),
      );
    } else if (index == 3) {
      return SizedBox(
        height: 500,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Center(
              child: Image.asset(
                'images/no_data.png',
                width: 175,
                height: 122,
              ),
            ),
          ],
        ),
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    _screenWidth = MediaQuery.of(context).size.width;
    return Stack(
      children: [
        Scaffold(
          appBar: AppBar(
            iconTheme: const IconThemeData(color: Colors.black),
            title: Text(
              "通讯录",
              style: TextStyle(
                  fontSize: 18,
                  color: ThemeColor.textColor,
                  fontWeight: FontWeight.bold),
            ),
            centerTitle: true,
            elevation: 0,
            bottom: TabBar(
              labelColor: ThemeColor.textColor,
              indicatorColor: ThemeColor.colorCF8F23,
              indicatorSize: TabBarIndicatorSize.label,
              unselectedLabelColor: ThemeColor.checkNormalColor,
              controller: _tabController,
              isScrollable: false,
              labelStyle:
                  TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
              unselectedLabelStyle:
                  TextStyle(color: ThemeColor.textColor, fontSize: 14),
              tabs: _tabs.map((choice) {
                return Tab(
                  text: choice,
                );
              }).toList(),
            ),
            backgroundColor: Colors.white,
            actions: [
              GestureDetector(
                  onTap: () {
                    Get.to(AddIndex(
                      refreshBlock: () {
                        if (lists.isNotEmpty) {
                          lists.clear();
                          initdata();
                          _getListData(_page, 0);
                        }
                      },
                    ));
                  },
                  child: SizedBox(
                      width: 56,
                      height: 56,
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Container(
                            color: Colors.black,
                            width: 14,
                            height: 14,
                          ),
                          Image.asset(
                            'images/ic_addgroup.png',
                            width: 34,
                            height: 34,
                          ),
                        ],
                      )))
            ],
          ),
          backgroundColor: Colors.white,
          body: Column(
            children: [
              Expanded(
                flex: 1,
                child: TabBarView(
                  physics: const NeverScrollableScrollPhysics(),
                  controller: _tabController,
                  children: _tabs.map((choice) {
                    return RefreshIndicator(
                      onRefresh: _onRefresh,
                      child: _listData.isNotEmpty
                          ? ListView.builder(
                              controller: _scrollController,
                              padding: const EdgeInsets.all(8.0),
                              itemCount: _listData.length,
                              itemBuilder: (BuildContext context, int index) {
                                if (index == _listData.length) {
                                  //加载更多
                                  return _getMoreWidget();
                                } else {
                                  if (_listData.isNotEmpty == true) {
                                    return _buildItems(
                                        _listData[index], choice, index);
                                  } else {
                                    return Container();
                                  }
                                }
                              })
                          : gettype(_index),
                    );
                  }).toList(),
                ),
              ),
              // Expanded(child: _buildListView())
            ],
          ),
        ),
        Positioned(
          child: GetBuilder(
              id: contactMainController.showPermissionViewId,
              builder: (ContactMainController mainController) {
                return Visibility(
                  visible: mainController.isShowPermission,
                  child: GestureDetector(
                    onTap: () {
                      mainController.isShowPermission = false;
                      mainController
                          .update([contactMainController.showPermissionViewId]);
                    },
                    child: Container(
                      width: 1.sw,
                      height: 1.sh,
                      color: const Color.fromRGBO(0, 0, 0, 0.2),
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.only(
                                left: 30, top: ScreenUtil().statusBarHeight),
                            width: 1.sw,
                            height: 90,
                            color: Colors.white,
                            child: const Text(
                              '位置权限说明\n获取您当前的位置，为您匹配附近的商家',
                              style: TextStyle(fontSize: 16),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              }),
        ),
      ],
    );
  }

  Future<bool> locationStatus() async {
    final status = await Permission.location.status;
    if (status.isGranted) {
      return false;
    }
    return true;
  }

  /// 获取列表数据
  _getListData(
    int page,
    int index,
  ) async {
    switch (index) {
      case 0:
        //好友
        final easeName = await Provider.getUserEaseName();
        if (kDebugMode) {
          print('rx--环信用户id-------' + Provider.userEaseName);
        }
        if (easeName.isEmpty) return;
        loading(() async {
          final res =
              await Api.getInstance().getFriendList(Provider.userEaseName);
          final data = res['data'];
          if (data != null) {
            List list = data;
            if (list.isNotEmpty) {
              _listData.clear();
              setState(() {
                _listData.addAll(list);

                if (kDebugMode) {
                  print('---111-----------' + _listData.length.toString());
                }
              });
            }
          } else {
            if (kDebugMode) {
              print('------通讯录异常记录---------------' + res['msg']);
            }
          }
        });
        //获取好友列表成功后调用群列表后台加缓存
        await Api.getInstance().getGroupList(Provider.userEaseName);

        break;
      case 1:
        //粉丝
        loading(() async {
          final easeName = await Provider.getUserEaseName();
          if (kDebugMode) {
            print('rx--环信用户id-------' + Provider.userEaseName);
          }
          if (easeName.isEmpty) return;
          final res =
              await Api.getInstance().getFanLists(Provider.userEaseName);
          final data = res['data'];
          if (data != null) {
            List list = data;
            if (list.isNotEmpty) {
              _listData.clear();
              _listData.addAll(list);
              setState(() {});
            }
          } else {
            if (kDebugMode) {
              print('------通讯录异常记录---------------' + res['msg']);
            }
          }
        });

        break;
      case 2:
        //群聊
        loading(() async {
          final easeName = await Provider.getUserEaseName();
          if (kDebugMode) {
            print('rx--环信用户id-------' + Provider.userEaseName);
          }
          if (easeName.isEmpty) return;
          final res =
              await Api.getInstance().groupListsCache(Provider.userEaseName);
          final data = res['data'];
          if (data != null) {
            List list = data;
            if (list.isNotEmpty) {
              _listData.clear();
              _listData.addAll(list);
              setState(() {});
            }
          } else {
            if (kDebugMode) {
              print('------通讯录异常记录---------------' + res['msg']);
            }
          }
        });
        break;
      case 3:
        //商家
        loading(() async {
          var res =
              await HttpRequest.request('match-maker/business/querys', params: {
            'nearbyLon': contactMainController.longitude,
            'nearbyLat': contactMainController.latitude
          });
          final data = res['data'];
          if (data != null) {
            List list = data;
            if (list.isNotEmpty) {
              _listData.clear();
              for (Map element in list) {
                if (element['shortName'] != null) {
                  _listData.add(element);
                }
              }
              setState(() {});
            }
          } else {
            if (kDebugMode) {
              print('------通讯录异常记录---------------' + res['msg']);
            }
          }
        });
        break;
    }
  }

  void setMessagelist(List addmessage, String type) async {
    if (Provider.userEaseName.isEmpty || addmessage.isEmpty) return;
    //--类型 （1：消息，2：好友，3：粉丝，4：群聊， 5：新朋友）
    final res = await Api.getInstance()
        .addMessagelist(Provider.userEaseName, addmessage, type);

    if (res['code'] == 0) {
    } else {
      toast(res['msg']);
    }
  }

  //删除好友
  void deleteuser(String string, int index) async {
    final res = await Api.getInstance().deleteUsers(string);

    if (res['code'] == 0) {
      setState(() {
        _listData.removeAt(index);
      });
    } else {
      if (kDebugMode) {
        print('------通讯录异常记录---------------' + res['msg']);
      }
    }
  }

  Widget _buildSearchBar() {
    return GestureDetector(
      onTap: () {},
      child: Container(
          height: 32,
          margin: const EdgeInsets.symmetric(horizontal: 12),
          padding: const EdgeInsets.symmetric(horizontal: 24),
          decoration: ShapeDecoration(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16)),
              color: const Color(0xFFF7F7F7)),
          alignment: Alignment.centerLeft,
          child: IconText(
            "  搜索备注、昵称",
            style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 13),
            icon: const Icon(
              Icons.search_rounded,
              size: 15,
              color: Color(0xFFBABABA),
            ),
            beforeText: true,
          )),
    );
  }

  Widget getAddNewFriendsEmptyView(String imgStr) {
    return SizedBox(
      height: 500,
      width: 500,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Center(
            child: Image.asset(
              imgStr,
              width: 175,
              height: 122,
            ),
          ),
        ],
      ),
    );
  }

  _buildItems(Map map, String choice, int index) {
    bool isWoman = map['realSex'] == 2;
    String homeAddr = map['homeAddr'] ?? '地点未知';
    switch (_index) {
      case 0:
        {
          if (_listData != [] && _listData.isNotEmpty) {
            return GestureDetector(
              onTap: () {
                if (map['id'].toString().isEmpty) return;
                debugPrint('----$map');
                Get.to(
                  PersonInfo(sig: map['id'].toString()),
                  routeName: PageRouteNames.personInfoPage,
                );
              },
              child: Container(
                height: 70,
                margin: const EdgeInsets.symmetric(
                  horizontal: 12,
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ChatNetImage(
                        imageUrl: map['profilePhoto'],
                        width: 50.w,
                        height: 50.w,
                        radius: 6.w),
                    const SizedBox(
                      width: 8,
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 200,
                          child: Text(
                            map["nickName"] ?? "",
                            style: TextStyle(
                              color: ThemeColor.gray3A3A3AColor,
                              fontSize: 16,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(
                          height: 7,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          } else {
            return getAddNewFriendsEmptyView('images/ic_nofriend.png');
          }
        }
      case 1:
        {
          if (_listData != [] && _listData.isNotEmpty) {
            return GestureDetector(
              onTap: () {
                if (map['id'].toString().isEmpty) return;
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (builder) =>
                        PersonInfo(sig: map['id'].toString())));
              },
              child: Container(
                height: 70,
                margin: const EdgeInsets.symmetric(
                  horizontal: 12,
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ChatNetImage(
                        imageUrl: map['profilePhoto'],
                        width: 50.w,
                        height: 50.w,
                        radius: 6.w),
                    // ClipRRect(
                    //   borderRadius: BorderRadius.circular(6),
                    //   child: Image.network(map['profilePhoto'],
                    //       width: 50, height: 50, fit: BoxFit.cover),
                    // ),
                    const SizedBox(
                      width: 8,
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 200,
                          child: Text(
                            map["nickName"] ?? "",
                            style: TextStyle(
                              color: ThemeColor.gray3A3A3AColor,
                              fontSize: 16,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(
                          height: 7,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          } else {
            return getAddNewFriendsEmptyView('images/ic_fans.png');
          }
        }
      case 2:
        {
          if (_listData != [] && _listData.isNotEmpty) {
            if (map['memberEaseGroup'] == null) return;
            var memberEaseGroup = map['memberEaseGroup'];
            String groupTypeStr =
                memberEaseGroup['groupType'] == 1 ? '个人' : '商家';
            List<Color> personalColors = const [
              Color(0xFF5980FB),
              Color(0xFF2D95F6),
            ];
            List<Color> shopColors = const [
              Color(0xFFFB7659),
              Color(0xFFF6922D),
            ];
            List<Color> colors =
                memberEaseGroup['groupType'] == 1 ? personalColors : shopColors;

            return GestureDetector(
              onTap: () {
                if (_listData.isNotEmpty) {
                  debugPrint('----${memberEaseGroup['groupUrl']}');
                  Get.toNamed(PageRouteNames.meetGroupChat, arguments: {
                    'id': memberEaseGroup['groupId'].toString(),
                    'owner': '${memberEaseGroup['owner']}',
                    'title': '${memberEaseGroup['groupName']}(${map['count']})',
                    'avatarUrl': memberEaseGroup['groupUrl'],
                  });
                  // Get.to(
                  //     GroupChat(memberEaseGroup['groupId'].toString(),
                  //         _listData[index]['owner'].toString()),
                  //     routeName: PageRouteNames.groupChatPage);
                }
              },
              child: Container(
                height: 70,
                margin: const EdgeInsets.symmetric(horizontal: 12),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(5),
                      child: memberEaseGroup.isNotEmpty
                          ? ChatNetImage(
                              imageUrl: memberEaseGroup['groupUrl'],
                              width: 50.w,
                              height: 50.w,
                              fit: BoxFit.fill,
                            )
                          : Container(),
                    ),
                    const SizedBox(
                      width: 8,
                    ),
                    SizedBox(
                      width: 200,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            memberEaseGroup['groupName'].toString() ?? "",
                            style: TextStyle(
                              color: ThemeColor.gray3A3A3AColor,
                              fontSize: 16,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          const SizedBox(
                            height: 7,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Container(
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(36),
                                    color: ThemeColor.color19CF8F23),
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 8, vertical: 2),
                                child: IconText(
                                  map['count'] == null
                                      ? ' 0'
                                      : ' ${map['count'].toString()}',
                                  icon: Image.asset(
                                    'images/user/txl_ql_icon.png',
                                    width: 12,
                                    color: ThemeColor.appColor,
                                  ),
                                  style: TextStyle(
                                    color: ThemeColor.appColor,
                                    fontSize: 12,
                                  ),
                                ),
                              ),
                              const SizedBox(
                                width: 5,
                              ),
                              Text(
                                map['description'].toString() == 'null'
                                    ? ''
                                    : ' ${map['description'].toString()}',
                                style: TextStyle(
                                    color: ThemeColor.textColorSecond,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w600),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Expanded(child: Container()),
                  ],
                ),
              ),
            );
          } else {
            return const SizedBox(
                height: 500, width: 500, child: CommonEmptyView());
          }
        }
      case 3:
        {
          if (_listData != [] && _listData.isNotEmpty) {
            ShopMatchMakerListDataModel detailShopModel =
                ShopMatchMakerListDataModel.fromJson(map);
            int ornotOpen = detailShopModel.ornotOpen;
            String ornotOpenStr = ornotOpen == 0 ? '休息中' : '营业中';
            Color ornotOpenColor = ornotOpen == 0
                ? contactMainController.restTimeColor
                : ThemeColor.appColor;
            return Container(
              margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  detailShopModel.matchPhoto != null
                      ? ClipRRect(
                          borderRadius: BorderRadius.circular(5),
                          child: ChatNetImage(
                            imageUrl:
                                Provider.fixAvatar(detailShopModel.matchPhoto),
                            width: 50,
                            height: 50,
                            fit: BoxFit.cover,
                          ),
                        )
                      : Container(),
                  const SizedBox(
                    width: 12,
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        constraints:
                            BoxConstraints(maxWidth: 1.sw - 24 - 50 - 100),
                        child: Text(
                          detailShopModel.shortName ?? "",
                          style: TextStyle(
                              color: ThemeColor.gray3A3A3AColor,
                              fontSize: 16,
                              overflow: TextOverflow.ellipsis),
                        ),
                      ),
                      const SizedBox(
                        height: 7,
                      ),
                      Row(
                        children: [
                          Image.asset(
                            'images/user/locate_map_icon.png',
                            width: 13,
                          ),
                          Text(
                            detailShopModel.distance ?? '',
                            style: TextStyle(
                                color: ThemeColor.textColorSecond,
                                fontSize: 12),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Expanded(child: Container()),
                  Container(
                    width: 61,
                    height: 22,
                    decoration: BoxDecoration(
                        color: const Color(0xFFF9F7F7),
                        borderRadius: BorderRadius.circular(11)),
                    alignment: Alignment.center,
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: ornotOpenColor,
                          ),
                          width: 6,
                          height: 6,
                        ),
                        const SizedBox(
                          width: 3,
                        ),
                        Text(
                          ornotOpenStr,
                          style: TextStyle(color: ornotOpenColor, fontSize: 12),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          } else {
            return const SizedBox(
              height: 500,
              width: 500,
              child: CommonEmptyView(),
            );
          }
        }
    }
  }

  void getCurrentLocation() async {
    /// [hasShow] 隐私权政策是否弹窗展示告知用户
    AMapFlutterLocation.updatePrivacyShow(true, true);

    /// [hasAgree] 隐私权政策是否已经取得用户同意
    AMapFlutterLocation.updatePrivacyAgree(true);

    /// 动态申请定位权限
    requestPermission();
    AMapFlutterLocation.setApiKey(
        MapCommonConfig.androidKey, MapCommonConfig.iosMapKey);

    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    _startLocation();

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      double latitude = double.parse(result['latitude'].toString());
      double longitude = double.parse(result['longitude'].toString());
      contactMainController.longitude = longitude;
      contactMainController.latitude = latitude;
      _listData == [];
      _listData.clear();
      _getListData(_page, _tabs.length - 1);
      ;
    });
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }

  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      ///开始定位之前设置定位参数
      _setLocationOption();
      _locationPlugin.startLocation();
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = true;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;

      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 2000;

      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值：<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.HundredMeters;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }
}
